package com.cucn.ingmall.ware.service.impl;

import com.cucn.common.constant.ware.WareConstant;
import com.cucn.ingmall.ware.entity.PurchaseDetailEntity;
import com.cucn.ingmall.ware.service.PurchaseDetailService;
import com.cucn.ingmall.ware.service.WareSkuService;
import com.cucn.ingmall.ware.vo.PurchaseDoneVO;
import com.cucn.ingmall.ware.vo.PurchaseItemDoneVO;
import com.cucn.ingmall.ware.vo.PurchaseMergeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cucn.common.utils.PageUtils;
import com.cucn.common.utils.Query;

import com.cucn.ingmall.ware.dao.PurchaseDao;
import com.cucn.ingmall.ware.entity.PurchaseEntity;
import com.cucn.ingmall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取的采购单
     *
     * @param params 请求参数
     * @return 查询出的带分页的数据
     */
    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0).or().eq("status", 1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 采购需求合并到采购单
     *
     * @param purchaseMergeVO 合并采购需求VO对象
     */
    @Override
    @Transactional
    public void mergePurchase(PurchaseMergeVO purchaseMergeVO) {
        Long purchaseId = purchaseMergeVO.getPurchaseId();
        //如果采购单为空,必须新建一个采购单之后进行合并
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //KouTODO:2021/12/6 17:30 Kou 确认采购单状态是0或1才可以合并
        PurchaseEntity byId = this.getById(purchaseId);
        if (byId.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                byId.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
            //采购需求的id
            List<Long> items = purchaseMergeVO.getItems();

            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> purchaseDetailList = items.stream()
                    .map(detailId -> {
                        PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                        purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                        purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                        purchaseDetailEntity.setId(detailId);
                        return purchaseDetailEntity;
                    }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailList);
        }

    }

    /**
     * 采购人员领取采购单
     *
     * @param purchaseIds 采购单id集合
     */
    @Override
    @Transactional
    public void received(List<Long> purchaseIds) {
        //1.确认采购单是新建或者是已分配状态
        List<PurchaseEntity> purchaseList = purchaseIds.stream()
                .map(ids -> this.getById(ids))
                .filter(item -> item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                        item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .peek(item -> item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode()))
                .collect(Collectors.toList());
        //2.改变采购单状态
        this.updateBatchById(purchaseList);

        //3.改变采购需求状态
        purchaseList.forEach(item -> {
            purchaseDetailService.updateListDetailByPurchaseId(item.getId());
        });
    }

    /**
     * 采购人员完成采购单
     *
     * @param doneVO 完成采购单vo对象
     */
    @Override
    @Transactional
    public void done(PurchaseDoneVO doneVO) {
        //2.改变采购需求的状态
        List<PurchaseItemDoneVO> items = doneVO.getItems();

        boolean flag = true;
        List<PurchaseDetailEntity> itemList = new ArrayList<>();
        for (PurchaseItemDoneVO item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getItemId());
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERR.getCode()) {
                flag = false;
                purchaseDetailEntity.setStatus(item.getStatus());
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3.将成功采购的进行入库
                PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(item.getItemId());
                //商品id,仓库id,入库商品数量
                wareSkuService.addStock(purchaseDetail.getSkuId(), purchaseDetail.getWareId(), purchaseDetail.getSkuNum());
            }
            itemList.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(itemList);

        //1.改变采购单状态
        //采购单的状态要根据采购项的状态走
        Long purchaseId = doneVO.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERR.getCode());
        this.updateById(purchaseEntity);
    }
}